<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* html,body{
            width: 100%;
            height: 100%;
        } */
        .box{
            width: 100px;
            height: 100px;
            background-color: chartreuse;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="box"></div>


    <script>
        //获取元素
        var box = document.querySelector('.box')
        //鼠标按下事件
        box.onmousedown = function(){
            // console.log('按下')

            //按下移动
            window.onmousemove = function(e){

                //兼容模式写法
                e = e || window.event

                //获取盒子的大小的一半
                // var i = 
                // var j = 


                //获取鼠标在窗口的坐标
                var x = e.clientX - box.offsetWidth / 2
                var y = e.clientY - box.offsetHeight / 2
                // console.log(x,y)

                //获取可视窗口的大小
                //不让盒子离开可时窗口
                if ( x >= document.documentElement.clientWidth - box.offsetWidth) {
                    x = document.documentElement.clientWidth - box.offsetWidth
                }
                if (y >= document.documentElement.clientHeight - box.offsetHeight) {
                    y = document.documentElement.clientHeight - box.offsetHeight
                }
                if (x <= 0) {
                    x = 0
                }
                if (y <= 0) {
                    y= 0
                }

                //把鼠标坐标赋值给盒子的left 和 top
                box.style.left = x + 'px'
                box.style.top =  y  + 'px'
            }
        }

        //鼠标抬起时 取消移动事件
        window.onmouseup = function(){

            //清除移动事件
            window.onmousemove = 0
        }
        
        
        
        
        
        
        </script>
</body>
</html>